<?php
/**
 * File
 * @author Erko Risthein <erko@risthein.ee>
 * @copyright Copyright (C) 2009 Erko Risthein
 * @link http://erko.risthein.ee/decode/
 * @license http://www.gnu.org/licenses/ GNU General Public License
 * @package decode_explorer
 */
class File extends Filesystem {
	private $size;
	private $size_in_bytes;
	private $extension;
	private $icon;
	
	/**
	 * @param string $path to the file
	 */
	function __construct($path) {
		parent::__construct($path);
		$this->size_in_bytes = $this->get_filesize($path);
		$this->extension = $this->extract_extension($this->name);
		$this->icon = Icons::get($this->extension);
		//data formatting
		$this->name = $this->trim_name($this->name);
		$this->size = $this->size_in_bytes;
		Filesystem::format_filesize($this->size);
	}
	
	/**
	 * Extacts the file extension
	 * @param string $filename
	 * @return string extension
	 */
	private function extract_extension($filename) {
		return mb_strtolower(mb_substr($filename, mb_strripos($filename, '.') + 1));
	}
	
	/**
	 * Trims names longer than $length characters and adds the extension to the end
	 * @param string $name
	 * @param string $length maximum length
	 * @return string trimmed name
	 */
	public function trim_name($name, $length = 50) {
		if (mb_strlen($name) > $length) {
			$name = Helper::trim_name($name) . $this->extension;
		}
		return $name;
	}
	
	/**
	 * Gets the filesize in bytes (works with large filesizes)
	 * @param string $path to the file
	 * @return string filesize in bytes (as a string so it would work with large filesizes)
	 */
	private function get_filesize($path) {
		$size = @filesize($path); //files under 2GB
		if ($size === false || $size < 0) { //over 2GB
			if (strtoupper(substr(PHP_OS, 0, 3)) != 'WIN') { //Linux/mac
				if (function_exists('exec')) {
					$size = exec('stat -c %s ' . escapeshellarg($path));
				}
			} else { //Windows
				try {
					$filesystem = new COM('Scripting.FileSystemObject');
					$file = $filesystem->getFile(realpath($path));
					$size = $file->size;
				} catch (Exception $e) {}
			}
		}
		return $size;
	}
	
	/**
	 * @return string formatted file size
	 */
	public function get_size() {
		return $this->size;
	}
	
	/**
	 * @return string filesize in bytes (as a string so it would work with large filesizes)
	 */
	public function get_size_in_bytes() {
		return $this->size_in_bytes;
	}
	
	/**
	 * @return string icon file name
	 */
	public function get_icon() {
		return $this->icon;
	}
}
?>